/**
 * UploadActions.java
 *
 * Copyright (C) 2009,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package extjsdyntran.servlets.actions;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import extjsdyntran.translation.TranslationFactory;

import extjsdyntran.servlets.Constants;
import ws4is.servlets.engine.AbstractAction;
import ws4is.servlets.engine.HTTPRequestType;

public final class UploadActions extends AbstractAction {

	final static Logger logger = LoggerFactory.getLogger(UploadActions.class);
	private String language = null;
	
	/******************************************
	 * 			POJO Methods     		      * 
	 ******************************************/
	public void setLanguage(final String language){
		this.language = language;
	}
	
	/******************************************
	 * 			overrides        		      * 
	 ******************************************/
	@Override
	public String preExecute(HTTPRequestType type, HttpServletRequest request) {
		if (type == HTTPRequestType.POST){
			return "xaction";
		}else 	return "cmd";
	}
	
	
	@Override
	public void postExecute(HTTPRequestType type, String method, Exception e) {
		// TODO Auto-generated method stub
	}
	
	/******************************************
	 * 			HTTP-GET Methods		      * 
	 ******************************************/		
	//http://.../servlet?action=UploadActions&cmd=export
	public void exportLang(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		try{
			doExport(request,response);
		}catch(Exception e){
			logger.error("Error exporting language translations...",e);
		}
	}
		
	
	/******************************************
	 * 			HTTP-POST Methods		      * 
	 ******************************************/
	//http://.../servlet?action=UploadActions&cmd=importLang
	public void importLang(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		setJsonResponseHeader(response);

		// UTF-8 writer
		PrintWriter pw = getPrintWriter(response);
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);		
		if (isMultipart){
			try{
				if (doImport(request)) {
					pw.print(Constants.json_true);	
				} else pw.print(getJSONResponse(false, Constants.err10)); 
				
			}catch(Exception e){
				pw.print(getJSONResponse(false, e.getMessage()));
				logger.error("Error importing language translations...",e);
			}
			
			closePrintWriter(pw);
			return;
		}
	}

	
	/******************************************
	 * 			Private Methods		      * 
	 ******************************************/
	//compress language cache files and send to client
	public void doExport(HttpServletRequest request,HttpServletResponse response) throws Exception {

		setJsonResponseHeader(response);
		boolean isSingle = language!=null; 
		ByteArrayOutputStream bout = null;
		
		if (isSingle) {
			response.setHeader("Content-Disposition","inline; filename="+language+".transl;");
			TranslationFactory.saveLanguages(language);
			bout = TranslationFactory.compressCache(language);
		}else{
			response.setHeader("Content-Disposition","inline; filename=all.transl;");
			TranslationFactory.saveLanguages("*");
			bout = TranslationFactory.compressCache(null);
		}

		response.setContentType("application/zip");		
		ServletOutputStream out = response.getOutputStream(); 
		out.write(bout.toByteArray());
        out.flush();
	}

	//receive compressed language files;decompress to cache
	public boolean doImport(HttpServletRequest request ) throws Exception {
		
		
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<?> items = upload.parseRequest(request);
		Iterator<?> iter = items.iterator();
		while (iter.hasNext()) {
		    FileItem item = (FileItem) iter.next();

		    if (item.isFormField()) {
		    	
		    } else {
				try{
					if (TranslationFactory.deCompressCache(item)){
						TranslationFactory.saveLanguages("*");
						return true;
					}
					return false;
				}catch(Exception e ){
					logger.error("Error importing language translations (maybe invalid file format)...",e);
				}
		    }
		}
		
		return false;
		
	}
	
}
